package week12;

import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;

public class AllPossible {

	private Queue<String> in;
	private Queue<String> out;
	private Stack<String> stack;

	private int numPossible;

	public AllPossible(String str) {

		in = new LinkedList<>();
		out = new LinkedList<>();
		stack = new Stack<>();

		numPossible = 0;

		String[] tokens = str.substring(0, str.length() - 1).split(",");

		// for (int i = tokens.length - 1; i >= 0; i--) {
		for (int i = 0; i < tokens.length; i++) {
			in.add(tokens[i]);
		}

	}

	public void all() {
		all(in, stack, out);

		System.out.println(String.format("Total possible: %d", numPossible));
	}

	private void show(Queue<String> out) {
		System.out.println(out);
	}

	private void all(Queue<String> in, Stack<String> stack, Queue<String> out) {

		if (in.isEmpty()) {
			if (stack.empty()) {
				numPossible++;
				show(out);
			} else {
				out.add(stack.pop());

				all(in, stack, out);
			}
		} else {
			if (!stack.empty()) {
				Stack<String> ts = new Stack<>();
				Queue<String> tin = new LinkedList<>();
				Queue<String> tout = new LinkedList<>();

				tin.addAll(in);
				ts.addAll(stack);
				tout.addAll(out);

				tout.add(ts.pop());
				all(tin, ts, tout);
			}
			stack.push(in.poll());
			all(in, stack, out);
		}

	}

	public static void main(String[] args) {

		if (args.length == 1) {
			AllPossible allPossible = new AllPossible(args[0]);
			allPossible.all();
		} else {
			System.out.println("Error:Please enter the string!");
		}
		

	}

}
